﻿using SealManagement.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace SealManagement.Common
{
    public class ToolClass
    {
        /// <summary>
        /// 用DES进行加密
        /// </summary>
        /// <param name="inData">要加密的内容</param>
        /// <returns>加密后内容</returns>
        public static byte[] Encrypt(byte[] inData)
        {
            try
            {
                //这个key值和IV值是固定的8位长度，一定要牢记。因为咱们的参数sKey是不定长度的、所以采取了一个方式就是对其进行MD5加密、然后再截取他的前8位。这是为了在解密的时候保证key一致。不然会解密出错。
                //des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
                //des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8));
                byte[] btKey = Encoding.ASCII.GetBytes("gongxing");
                byte[] btIV = btKey;
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                using (MemoryStream ms = new MemoryStream())
                {
                    try
                    {
                        using (
                            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(btKey, btIV),
                                CryptoStreamMode.Write))
                        {
                            cs.Write(inData, 0, inData.Length);
                            cs.FlushFinalBlock();
                        }
                        return ms.ToArray();
                    }
                    catch
                    {
                        return null;
                    }
                }
            }
            catch
            {
                return null;
            }
        }


        ///<summary>
        /// 用DES进行解密
        /// </summary>
        /// <param name="inData">要解密的内容</param>
        /// <returns>解密后的内容</returns>
        public static byte[] Decrypt(byte[] inData)
        {
            try
            {
                byte[] btKey = Encoding.ASCII.GetBytes("gongxing");
                byte[] btIV = btKey;
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                using (MemoryStream ms = new MemoryStream())
                {
                    try
                    {
                        using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(btKey, btIV), CryptoStreamMode.Write))
                        {
                            cs.Write(inData, 0, inData.Length);
                            cs.FlushFinalBlock();
                        }
                        return ms.ToArray();
                    }
                    catch
                    {
                        return null;
                    }
                }
            }
            catch (Exception)
            {
                return null;
            }
        }

        /// <summary>
        /// 生成随机数
        /// </summary>
        /// <param name="length">指定随机数的长度</param>
        /// <returns></returns>
        public static string CreateValidateCode(int length)
        {
            int[] randMembers = new int[length];
            int[] validateNums = new int[length];
            string validateNumberStr = "";
            //生成起始序列值
            int seekSeek = unchecked((int)DateTime.Now.Ticks);
            Random seekRand = new Random(seekSeek);
            int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000);
            int[] seeks = new int[length];
            for (int i = 0; i < length; i++)
            {
                beginSeek += 10000;
                seeks[i] = beginSeek;
            }
            //生成随机数字
            for (int i = 0; i < length; i++)
            {
                Random rand = new Random(seeks[i]);
                int pownum = 1 * (int)Math.Pow(10, length);
                randMembers[i] = rand.Next(pownum, Int32.MaxValue);
            }
            //抽取随机数字
            for (int i = 0; i < length; i++)
            {
                string numStr = randMembers[i].ToString();
                int numLength = numStr.Length;
                Random rand = new Random();
                int numPosition = rand.Next(1, numLength - 1);//length过大，pownum为负数，生成的随机数字存在负数，取0位是一个负数符号
                validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
            }
            //生成验证码
            for (int i = 0; i < length; i++)
            {
                validateNumberStr += validateNums[i].ToString();
            }
            return validateNumberStr;
        }

        public static HttpWebResponse CreatePostHttpResponse(string url, string data, string method = "POST")
        {
            var webRequest = HttpWebRequest.Create(url) as HttpWebRequest;
            //webRequest.ProtocolVersion = HttpVersion.Version10;
            webRequest.Method = method ?? "post";
            webRequest.ContentType = "application/json;charset=UTF-8";
            if (!string.IsNullOrEmpty(data))
            {
                byte[] dataBytes = Encoding.UTF8.GetBytes(data);
                using (Stream stream = webRequest.GetRequestStream())
                {
                    stream.Write(dataBytes, 0, dataBytes.Length);
                }
            }
            return webRequest.GetResponse() as HttpWebResponse;
        }

        public static string EncryptTransit(string EncryptData)
        {
            string res = string.Empty;
            #region CodeForLocalTest
            //var privateKey = "laWZDy8pHBqC6yiugc/zC0KRufQ+1bKntkGUdiFQFz4=";
            //var privateKeyBytes = Convert.FromBase64String(privateKey);
            //var encryptBytes = Convert.FromBase64String(EncryptData);
            //byte[] dataBytes = null;
            //try
            //{
            //    dataBytes = SMToolClass.Decrypt(privateKeyBytes, encryptBytes);
            //}
            //catch (Exception e)
            //{
            //    return res;
            //}
            //res = Encoding.UTF8.GetString(dataBytes);
            #endregion

            #region CodeForServerTest
            var encryptBytes = Convert.FromBase64String(EncryptData);
            byte[] plainTextBytes = new byte[encryptBytes.Length];
            int plainTextBytesLength = plainTextBytes.Length;
            var a = 0;
            lock (GMSealDll.Lock)
            {
                a = GMSealDll.SGD_ExtAndDateDecrypt(encryptBytes, encryptBytes.Length, plainTextBytes, ref plainTextBytesLength);
            }
            if (a != 0)
            {
                return a.ToString();
            }
            res = Encoding.UTF8.GetString(plainTextBytes);
            #endregion
            return res;
        }

        public static string GetDescription(Enum obj)
        {
            string objName = obj.ToString();
            Type t = obj.GetType();
            FieldInfo fi = t.GetField(objName);
            DescriptionAttribute[] arrDesc = null;
            try
            {
                arrDesc = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            }
            catch (Exception)
            {
                return "";
            }
            return arrDesc[0].Description;
        }
    }
}
